﻿using AutoMapper;

using B.S.Traceability.Domain;
using B.S.Traceability.Error;
using B.S.Traceability.Infrastructure.Interface;
using B.S.Traceability.Read.API.Application.Commends.Farm;
using B.S.Traceability.Read.API.Dto;
using MediatR;

namespace B.S.Traceability.Read.API.Application.CommendHandlers.Farm
{
    public class GetFarmsCommendHandlers : IRequestHandler<GetFarmsCommends, APIResult<List<ProductFarmsDto>>>
    {

        private readonly IBaseRepository<Farms> farmRepository;
        private readonly IBaseRepository<Shoops> shoopsRepository;
        private readonly IBaseRepository<Products> productsRepository;
        private readonly IBaseRepository<IntegrateImgs> integrateRepository;
        private readonly IMapper mapper;

        public GetFarmsCommendHandlers(IBaseRepository<Farms> farmRepository, IBaseRepository<Shoops> shoopsRepository, IBaseRepository<Products> productsRepository, IBaseRepository<IntegrateImgs> integrateRepository, IMapper mapper)
        {
            this.farmRepository = farmRepository;
            this.shoopsRepository = shoopsRepository;
            this.productsRepository = productsRepository;
            this.integrateRepository = integrateRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 获取养殖场信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<ProductFarmsDto>>> Handle(GetFarmsCommends request, CancellationToken cancellationToken)
        {
            APIResult<List<ProductFarmsDto>> result = new APIResult<List<ProductFarmsDto>>();
            result.Code = APIEnum.查询成功;
            result.Msg = "查询成功";

            var products = productsRepository.GetAllAsync().Result;
            var farms = farmRepository.GetAllAsync().Result;
            var lists =from a in farms join b in products on a.BatchId equals b.BatchId
                       where a.BatchId == request.BatchId
                       select new ProductFarmsDto
                        {
                            FarmsId = a.FarmsId,
                            BatchId = a.BatchId,
                            Variety = a.Variety,
                            Source = a.Source,
                            RearsNum = a.RearsNum,
                            Feedbrands = a.Feedbrands,
                            FeedPerson = a.FeedPerson,
                           SlaughterTime= a.SlaughterTime,


                       };
            var data = mapper.Map<List<ProductFarmsDto>>(lists);

            result.data = data.ToList();
            return Task.FromResult(result);
        }
    }
}
